<template>
  <div>
    <el-dialog
        v-model="visibleModel"
        title="送货单"
        width="900"
        style="height:70%;display:flex;flex-direction:column;justify-content:space-between;"
        align-center
        draggable
        overflow
        :before-close="handleClose"
        :close-on-click-modal="false"
    >
        <template #header>
            <!-- <div> -->
            <span v-if="props.deliveryType === 'add'">创建送货单</span>
            <span v-if="props.deliveryType === 'edit'">编辑送货单</span>
            <div class="btn-list" v-if="props.deliveryType === 'edit'">
                <el-button size="small" :icon="DocumentCopy">复制</el-button>
                <el-button
                    size="small" icon="delete"
                >
                    删除
                </el-button>
                <el-button
                    size="small" :icon="Printer"
                    @click="handlePrint"
                >
                    打印
                </el-button>
            </div>
            <!-- </div> -->
        </template>
        <el-form :model="deliveryStore.delivery" label-position="top" ref="deliveryRef" :rules="deliveryRules">
            <div class="form-container">
                <el-form-item label="销售订单" style="font-weight: bold;">
                    <el-button 
                        type="primary" plain
                        style="width: 250px;"
                        @click="handleSelectOrder"
                    >
                        选择订单数据
                    </el-button>
                </el-form-item>
                <el-form-item label="客户" prop="clientName">
                    <el-input 
                        v-model="deliveryStore.delivery.clientName"
                        style="width: 250px;"
                        placeholder="暂无数据"
                        disabled
                    />
                </el-form-item>
                <el-form-item label="商品名称" prop="skuName">
                    <el-input 
                        v-model="deliveryStore.delivery.skuName"
                        style="width: 250px;"
                        placeholder="暂无数据"
                        disabled
                    />
                </el-form-item>
            </div>
            <div class="form-container">
                <el-form-item label="牌号/款式" prop="skuBrand">
                    <el-input 
                        v-model="deliveryStore.delivery.skuBrand"
                        style="width: 180px;"
                        placeholder="暂无数据"
                        disabled
                    />
                </el-form-item>
                <el-form-item label="内部牌号" prop="internalBrand">
                    <el-input 
                        v-model="deliveryStore.delivery.internalBrand"
                        style="width: 180px;"
                        placeholder="暂无数据"
                        disabled
                    />
                </el-form-item>
                <el-form-item label="规格型号" prop="specification">
                    <el-input 
                        v-model="deliveryStore.delivery.specification"
                        style="width: 180px;"
                        placeholder="暂无数据"
                        disabled
                    />
                </el-form-item>
                <el-form-item label="订货金额" prop="amount">
                    <el-input 
                        v-model="deliveryStore.delivery.amount"
                        style="width: 180px;"
                        placeholder="暂无数据"
                        disabled
                    />
                </el-form-item>
            </div>
            <div class="form-container">
                <el-form-item label="订货量" prop="quantity">
                    <el-input 
                        v-model="deliveryStore.delivery.quantity"
                        style="width: 180px;"
                        placeholder="暂无数据"
                        disabled
                    />
                </el-form-item>
                <el-form-item label="订货单位" prop="unit">
                    <el-select 
                        v-model="deliveryStore.delivery.unit" 
                        style="width: 180px;"
                        disabled
                        placeholder="暂无数据"
                    >
                        <el-option label="pcs" value="pcs" />
                        <el-option label="kg" value="kg" />
                    </el-select>
                </el-form-item>
                <el-form-item label="订货重量" prop="weight">
                    <el-input 
                        v-model="deliveryStore.delivery.weight"
                        style="width: 180px;"
                        placeholder="暂无数据"
                        disabled
                    />
                </el-form-item>
                <el-form-item label="订货单价" prop="unitPrice">
                    <el-input 
                        v-model="deliveryStore.delivery.unitPrice"
                        style="width: 180px;"
                        placeholder="暂无数据"
                        disabled
                    />
                </el-form-item>
            </div>
            <div class="form-container">
                <el-form-item label="应送" prop="shouldDeliver">
                    <el-input
                        v-model="deliveryStore.delivery.shouldDeliver"
                        style="width: 180px;"
                        placeholder="暂无数据"
                        disabled
                    />
                </el-form-item>
                <el-form-item label="欠送" prop="oweDeliver">
                    <el-input
                        v-model="deliveryStore.delivery.oweDeliver"
                        style="width: 180px;"
                        placeholder="暂无数据"
                        disabled
                    />
                </el-form-item>
                <el-form-item label="库存量 (pcs)" prop="inventoryPcs">
                    <el-input
                        v-model="deliveryStore.delivery.inventoryPcs"
                        style="width: 180px;"
                        placeholder="暂无数据"
                        disabled
                    />
                </el-form-item>
                <el-form-item label="库存量 (kg)" prop="inventoryWeight">
                    <el-input
                        v-model="deliveryStore.delivery.inventoryWeight"
                        style="width: 180px;"
                        placeholder="暂无数据"
                        disabled
                    />
                </el-form-item>
            </div>
            <div class="form-container">
                <el-form-item label="本次送" prop="thisDeliver">
                    <el-input
                        v-model="deliveryStore.delivery.thisDeliver"
                        style="width: 180px;"
                        placeholder="暂无数据"
                        @input="handleInputThisDeliver"
                    />
                </el-form-item>
                <el-form-item label="送货日期" prop="deliverDt">
                    <el-date-picker
                        v-model="deliveryStore.delivery.deliverDt"
                        style="width: 180px;"
                        type="datetime"
                        placeholder="选择送货日期"
                        clearable
                        format="YYYY-MM-DD HH:mm:ss"
                        value-format="YYYY-MM-DD HH:mm:ss"
                    />
                </el-form-item>
                <el-form-item label="本次送重量" prop="thisDeliverWeight" v-if="deliveryStore.delivery.unit === 'pcs' && deliveryStore.delivery.byQuantity == '0'">
                    <el-input
                        v-model="deliveryStore.delivery.thisDeliverWeight"
                        style="width: 180px;"
                    />
                </el-form-item>
            </div>
            
        </el-form>
        <orderListDialog v-model="orderVisible" ref="orderListDialogRef"/>
        <template #footer>
            <div style="align-self: start;">
                <el-button 
                  type="primary" style="min-width: 100px;"
                  :disabled="isSubmitting"
                  @click="handleSubmit(deliveryRef)"
                >
                    提交并打印
                </el-button>
                <el-button plain style="width: 100px;" @click="handleCancel">
                    取消
                </el-button>
            </div>
        </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, nextTick, h } from 'vue'
import { DocumentCopy, Printer } from '@element-plus/icons-vue'
import { useDeliveryStore } from '@/stores/sale/delivery'
import orderListDialog from './orderListDialog.vue'
import type { FormInstance } from 'element-plus'
import { insertDelivery, createApprovement } from '@/pages/home/views/sale/api/delivery'
import { ElMessage, ElMessageBox } from 'element-plus'
import * as CONFIG from '@/pages/home/views/sale/config/order'
import { transformRMB } from '@/pages/home/views/sale/utils/base'

const visibleModel = defineModel()
const deliveryStore = useDeliveryStore()
const deliveryRef = ref<FormInstance>()
const orderVisible = ref(false)
const deliveryRules = ref({
    clientName: [
        { required: true, message: '请选择客户', trigger: 'change' },
    ],
    skuName: [
        { required: true, message: '请选择商品', trigger: 'change' },
    ],
    skuBrand: [
        { required: true, message: '请选择牌号/款式', trigger: 'change' },
    ],
    internalBrand: [
        { required: true, message: '请选择内部牌号', trigger: 'change' },
    ],
    specification: [
        { required: true, message: '请选择规格型号', trigger: 'change' },
    ],
    amount: [
        { required: true, message: '请选择订货金额', trigger: 'change' },
    ],
    quantity: [
    { required: true, message: '请选择订货量', trigger: 'change' },
    ],
    unit: [
        { required: true, message: '请选择订货单位', trigger: 'change' },
    ],
    unitPrice: [
        { required: true, message: '请选择订货单价', trigger: 'change' },
    ],
    shouldDeliver: [
        { required: true, message: '请选择应送', trigger: 'change' },
    ],
    oweDeliver: [
        { required: true, message: '请选择欠送', trigger: 'change' },
    ],
    inventory: [
        { required: true, message: '请选择库存量', trigger: 'change' },
    ],
    inventoryPcs: [
        { required: true, message: '请选择库存量 (pcs)', trigger: 'change' },
    ],
    inventoryWeight: [
        { required: true, message: '请选择库存量 (kg)', trigger: 'change' },
    ],
    thisDeliver: [
        { required: true, message: '请输入本次送', trigger: 'change' },
        {   
            type: 'number', 
            message: '本次送必须为数值', 
            trigger: 'change', 
            transform: (value) => Number(value)
        },
        { 
            validator: (rule, value, callback) => {
                if(value <= 0){
                    callback(new Error("本次送必须大于0"));
                }
                else if(deliveryStore.delivery.unit === "pcs" && value > deliveryStore.delivery.inventoryPcs) {
                    callback(new Error("本次送必须小于等于库存量 (pcs)"));
                }
                else if(deliveryStore.delivery.unit === "kg" && value > deliveryStore.delivery.inventoryWeight) {
                    callback(new Error("本次送必须小于等于库存量 (kg)"));
                }
                // else if(value > deliveryStore.delivery.shouldDeliver){
                //     callback(new Error("本次送必须小于等于应送量"));
                // }
                else callback();
            }, 
            trigger: 'change' 
        }
    ],
    deliverDt: [
        { required: true, message: '请选择送货日期', trigger: 'change' },
    ],
    thisDeliverWeight: [
        { 
            validator: (rule, value, callback) => {
                if(deliveryStore.delivery.byQuantity === "0" && value > deliveryStore.delivery.inventoryWeight) {
                    callback(new Error("本次送重量需小于等于库存量(kg)"))
                }
                else callback();
            }, 
            trigger: 'change' 
        }
    ]
})
const isSubmitting = ref(false)
const orderListDialogRef = ref()

const props = defineProps<{
    deliveryType: string
    getTableData: () => Promise<void>
}>()

const handleSelectOrder = async () => {
    orderVisible.value = true
    await nextTick()
    orderListDialogRef.value.getTableData()
    orderListDialogRef.value.dragTable()
}
const handleClose = (done) => {
    deliveryStore.resetDelivery(deliveryRef)
    console.log(deliveryStore.delivery)
    done()
}
const handleCancel = () => {
    visibleModel.value = false
    deliveryStore.resetDelivery(deliveryRef)
}
const handleSubmit = async (formRef) => {
    isSubmitting.value = true
    if (!formRef) return
    formRef.validate(async(valid, fields) => {
        if (valid) {
            console.log('submit!')
            switch(props.deliveryType){
                case 'add': 
                {
                    if(deliveryStore.delivery.oweDeliver < 0){
                        try {
                            await ElMessageBox(
                                {
                                    title: '提示',
                                    message: h('div', null, [
                                        h('span', null, `本次送货量为 `),
                                        h('strong', null, deliveryStore.delivery.thisDeliver),
                                        h('span', null, `，应送量为 `),
                                        h('strong', null, deliveryStore.delivery.shouldDeliver),
                                        h('span', null, ` 。`),
                                        h('br'),
                                        h('span', null, `是否确定送货？ `),
                                    ]
                                    ),
                                    confirmButtonText: '确定',
                                    showCancelButton: true,
                                    cancelButtonText: '取消',
                                }
                            )
                        } catch (error) {
                            isSubmitting.value = false
                            return
                        }
                    }

                    const deliveryCopy = JSON.parse(JSON.stringify(deliveryStore.delivery))
                    deliveryCopy.thisDeliver = Number(deliveryCopy.thisDeliver)
                    deliveryCopy.thisDeliverWeight = Number(deliveryCopy.thisDeliverWeight)

                    if(deliveryCopy.unit === "kg"){
                        deliveryCopy.thisDeliverWeight = deliveryCopy.thisDeliver
                    }

                    if(deliveryCopy.byQuantity === "1"){
                        deliveryCopy.thisDeliverAmount = (deliveryCopy.unitPrice * deliveryCopy.thisDeliver).toFixed(2)
                    }
                    else if(deliveryCopy.unit === "kg"){
                        deliveryCopy.thisDeliverAmount = (deliveryCopy.unitPrice * deliveryCopy.thisDeliver).toFixed(2)
                    }
                    else if(deliveryCopy.unit === "pcs"){
                        deliveryCopy.thisDeliverAmount = deliveryCopy.thisDeliverWeight 
                            ? (deliveryCopy.unitPrice * deliveryCopy.thisDeliverWeight).toFixed(2)
                            : null
                    }
                    deliveryStore.delivery.thisDeliverAmount = deliveryCopy.thisDeliverAmount

                    try {
                        const res = await insertDelivery(deliveryCopy)
                        if(res.data.success === false){
                            ElMessage.error(`${res.data.errorCode}: ${res.data.errorMsg}`)
                            isSubmitting.value = false
                            return
                        }

                        deliveryStore.delivery.no = res.data.data
                        deliveryCopy.no = res.data.data

                        const matchType = deliveryCopy.skuName.match(CONFIG.SKU_SPEC.SPEC_DETECTION)
                        const deliveryType = matchType ? matchType[1] : "其他"

                        const isqb = (type) => {
                            switch(type){
                                case "镜":
                                case "环":
                                case "针":
                                case "其他":
                                    return 0
                                case "线":
                                case "带": 
                                case "丝":
                                    return 2
                                default:
                                    return 1
                            }
                        }

                        const approveRes = await createApprovement({
                            productId: deliveryCopy.skuId,
                            productName: deliveryCopy.skuName,
                            brandOrStyle: deliveryCopy.skuBrand,
                            internalBrand: deliveryCopy.internalBrand,
                            specification: deliveryCopy.specification,
                            isQuantityBased: isqb(deliveryType),
                            operationType: "2",
                            ...deliveryCopy.unit === "pcs" && { piece: deliveryCopy.thisDeliver },
                            ...deliveryCopy.thisDeliverWeight && { amount: deliveryCopy.thisDeliverWeight },
                            department: "Sale",
                            noteId: deliveryCopy.no,
                            description: "销售送货出库"
                        })
                        if(!approveRes.data.success){
                        ElMessage.error(`${approveRes.data.errorCode}: ${approveRes.data.errorMsg}`)
                        isSubmitting.value = false
                        return
                        }
                    }
                    catch(error){
                        ElMessage.error(error)
                        isSubmitting.value = false
                        return
                    }
                }
                break
            }
            handlePrint()
            await props.getTableData()
            deliveryStore.resetDelivery(deliveryRef)
            visibleModel.value = false
            isSubmitting.value = false
        }
        else {
            console.log('error submit!', fields)
            isSubmitting.value = false
        }
    })
}
const handlePrint = () => {
    visibleModel.value = false
    let cssStyle = document.createElement("style"); 
    cssStyle.innerHTML = `
        .container {
            width: 100%;
            height: 1000px;
        }
        .print {
            width: 600px;
            height: 350px;
            border: 1px black solid;
            background-color: #d9d9d9;
            -webkit-print-color-adjust: exact;
            padding: 10px;
            margin-bottom: 10px;
        }
        .title {
            font-size: 32px;
            font-weight: bold;
            display: flex;
            flex-direction: column;
            row-gap: 10px;
            align-items: center;
        }
        .desc { font-weight: 500; }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 30px;
        }
        @page {
            margin: 10px;
        }`;
    const delivery = deliveryStore.delivery
    const printContentHtml = `
        <div class="title">
            <span style="color: #f5222d; -webkit-print-color-adjust: exact;">制造业小微企业</span>
            <span>送货单</span>
        </div>
        <div style="display: flex; justify-content: space-between; align-items: center;">
            <div style="width: 220px; text-align: left;">客户名称: ${delivery.clientName}</div>
            <div style="width: 220px; text-align: center;">客户代号: ${delivery.clientCode}</div>
            <div style="width: 220px; text-align: right;">订单号: ${delivery.orderId}</div>
        </div>
        <table cellspacing="0" cellpadding="1" border="1">
            <thead>
                <tr>
                    <th style="width: 50px;">单号</th>
                    <th style="width: 120px;">商品</th>
                    <th style="width: 100px;">商品牌号</th>
                    <th style="width: 100px;">内部牌号</th>
                    <th style="width: 140px;">规格型号</th>
                    <th style="width: 70px;">单位</th>
                    <th style="width: 100px;">应送</th>
                    <th style="width: 100px;">欠送</th>
                    <th style="width: 100px;">本次送</th>
                    <th>送货日期</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td style="text-align: center;">${delivery.no}</td>
                    <td style="text-align: center;">${delivery.skuName}</td>
                    <td style="text-align: center;">${delivery.skuBrand}</td>
                    <td style="text-align: center;">${delivery.internalBrand}</td>
                    <td style="text-align: center;">${delivery.specification}</td>
                    <td style="text-align: center;">${delivery.unit}</td>
                    <td style="text-align: center;">${delivery.shouldDeliver}</td>
                    <td style="text-align: center;">${delivery.oweDeliver}</td>
                    <td style="text-align: center;">${delivery.thisDeliver}</td>
                    <td style="text-align: center;">${delivery.deliverDt}</td>
                </tr>
            </tbody>
        </table>
        <div style="display: flex; justify-content: space-between; align-items: center; margin: -20px 0 30px;">
            <div>金额：${delivery.thisDeliverAmount ?? "暂无金额"}</div>
            <div>金额（大写）：${transformRMB(delivery.thisDeliverAmount)}</div>
            <div>收货方签字：____________________</div>
        </div>
    `
    const iframe = document.createElement("iframe");
    iframe.setAttribute(
        "style",
        "position:absolute;width:0px;height:0px;left:-50px;top:-50px;"
    );
    document.body.appendChild(iframe)
    iframe.contentDocument.getElementsByTagName("head")[0].appendChild(cssStyle);
    iframe.contentDocument.body.innerHTML = "<div>" + printContentHtml + "</div>"
    iframe.contentDocument.close();
    iframe.contentWindow.focus();
    iframe.contentWindow.print();
    document.body.removeChild(iframe);
}
const disabledDate = (time: Date) => {
  return time.getTime() < Date.now() - 8.64e7
}

const handleInputThisDeliver = (value) => {
    if(!value || !Number.isFinite(Number(value)) || Number(value) < 0){
        deliveryStore.delivery.oweDeliver = deliveryStore.delivery.shouldDeliver
    }
    else if(deliveryStore.delivery.unit === "kg"){
        if(Number(value) > deliveryStore.delivery.inventoryWeight){
            deliveryStore.delivery.oweDeliver = deliveryStore.delivery.shouldDeliver
        }
        else deliveryStore.delivery.oweDeliver = Number((deliveryStore.delivery.shouldDeliver - Number(value)).toFixed(2))
    }
    else if(deliveryStore.delivery.unit === "pcs"){
        if(Number(value) > deliveryStore.delivery.inventoryPcs){
            deliveryStore.delivery.oweDeliver = deliveryStore.delivery.shouldDeliver
        }
        else deliveryStore.delivery.oweDeliver = Number((deliveryStore.delivery.shouldDeliver - Number(value)).toFixed(2))
    }
}

defineExpose({
    handleSelectOrder
})

</script>

<style scoped>
:deep(.el-dialog__body) {
    overflow: auto;
    flex: 1;
    --el-disabled-text-color: var(--el-text-color-regular);
}
:deep(.el-dialog__footer) {
    align-self: start;
}
.btn-list {
    width: 100%;
    height:35px;
    border-top: 1px solid #eee;
    border-bottom: 1px solid #eee;
    display: flex;
    align-items: center;
    margin-top: 10px;
    gap: 10px;
}
.form-container {
    display: flex;
    flex-flow: row wrap;
    column-gap: 30px;
}
</style>